import { ref } from 'vue';

export interface ListQueryParams {
  page?: number; // 当前页码
  size?: number; // 每页数量
  [key: string]: any; // 其他自定义参数
}

export interface Pagination {
  page: number;
  size: number;
  total: number;
  pages: number;
}

export function useList<T>(
  fetchApi: (_params: ListQueryParams) => Promise<any>,
  defaultParams: ListQueryParams = { page: 1, size: 20 }
) {
  const loading = ref(false);
  const error = ref<string | null>(null);
  const list = ref<T[]>([]);
  const total = ref(0);
  const pagination = ref<Pagination | null>(null);
  const params = ref({ ...defaultParams });

  async function query(customParams?: Partial<ListQueryParams>) {
    loading.value = true;
    error.value = null;
    try {
      const res = await fetchApi({ ...params.value, ...customParams });
      // 响应体格式：{ code, message, data: { ...listKey, pagination }, timestamp }
      if (res.code === 200 && res.data) {
        // 自动识别列表 key（排除 pagination）
        const { pagination: pageInfo, ...rest } = res.data;
        const listKey = Object.keys(rest).find((key) =>
          Array.isArray(rest[key])
        );
        list.value = listKey ? rest[listKey] : [];
        total.value = pageInfo?.total || 0;
        pagination.value = pageInfo || null;
      } else {
        error.value = res.message || '列表查询失败';
        list.value = [];
        total.value = 0;
        pagination.value = null;
      }
    } catch (e: any) {
      error.value = e?.message || '列表查询失败';
      list.value = [];
      total.value = 0;
      pagination.value = null;
    } finally {
      loading.value = false;
    }
  }

  function refresh() {
    setPage(1);
  }

  function setPage(page: number) {
    params.value.page = page;
    query();
  }

  function setPageSize(size: number) {
    params.value.size = size;
    query();
  }

  return {
    list,
    total,
    pagination,
    loading,
    error,
    params,
    query,
    refresh,
    setPage,
    setPageSize
  };
}
